package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;

import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.pojo.User;
import cn.edu.pzhu.javaweb.pojo.Userinfo;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.service.imp.UserServiceImp;
import cn.edu.pzhu.javaweb.util.Conver2MD5;

/**
 * Servlet implementation class RegistServlet
 */
@WebServlet("/regist")
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImp();
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		String username = request.getParameter("username"); //接收用户名
		String password = request.getParameter("password"); //接收密码
		String email = request.getParameter("email"); //接收邮箱
		String sex = request.getParameter("sex"); //接收性别
		String[] types = request.getParameterValues("type"); //接收关注类型
		String captcha = request.getParameter("captcha"); //接收验证码
		
		//合法性校验
		if(username==null || username.isEmpty() || password ==null || password.isEmpty()) {
			response.getWriter().print("<script>alert('信息不完整!');location.href='regist.jsp';</script>");	
			return;
		}
		
		String sec_password = Conver2MD5.getSHA256(Conver2MD5.getSHA256(username+password)+"pzhu");
		
		User user = new User(username, sec_password, 1);
		
		if(sex==null || sex.equals("")) {
			sex = "1";
		}
		
		Userinfo userinfo = new Userinfo(username, email, Integer.valueOf(sex), JSON.toJSONString(types) );
		
		// 验证码校验 - 从session获取真实的验证码
		HttpSession session = request.getSession();
		String sessionCaptcha = (String) session.getAttribute("captcha");
		
		// 检查验证码是否为空或已过期
		if (sessionCaptcha == null) {
			response.getWriter().print("<script>alert('验证码已过期，请刷新后重试!');location.href='regist.jsp';</script>");
			return;
		}
		
		// 检查用户输入的验证码是否正确（忽略大小写）
		if (sessionCaptcha.equalsIgnoreCase(captcha)) {
			// 验证码正确，进行注册操作
			Result<String> result = userService.regist(user, userinfo);
			
			if (result.getCode() == 0) {
				// 注册成功，清除session中的验证码（防止重复使用）
				session.removeAttribute("captcha");
				response.getWriter().print("<script>alert('注册成功');location.href='login.jsp';</script>");
			} else {
				// 注册失败
				String errorMsg = result.getMsg() != null ? result.getMsg() : "注册失败";
				response.getWriter().print("<script>alert('" + errorMsg + "');location.href='regist.jsp';</script>");	
			}
		} else {
			// 验证码不正确
			response.getWriter().print("<script>alert('验证码不正确!');location.href='regist.jsp';</script>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}